using MediatR;
using UniversalAdmin.Application.Common;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Domain.Interfaces;

namespace UniversalAdmin.Application.Features.Menus.Queries.GetPagedMenus;

public class GetPagedMenusQueryHandler : IRequestHandler<GetPagedMenusQuery, ApiResult<PagedResult<MenuFlatDto>>>
{
  private readonly IUnitOfWork _uow;

  public GetPagedMenusQueryHandler(IUnitOfWork uow)
  {
    _uow = uow;
  }

  public async Task<ApiResult<PagedResult<MenuFlatDto>>> Handle(GetPagedMenusQuery request, CancellationToken ct)
  {
    // 一次性获取所有菜单（内存分页，适合中小数据量）
    var allMenus = await _uow.MenuRepository.GetAllAsync();

    if (!string.IsNullOrWhiteSpace(request.Keyword))
      allMenus = allMenus.Where(m => m.Name.Contains(request.Keyword, StringComparison.OrdinalIgnoreCase));

    if (request.IsActive.HasValue)
      allMenus = allMenus.Where(m => m.IsActive == request.IsActive.Value);

    if (request.ParentId.HasValue)
      allMenus = allMenus.Where(m => m.ParentId == request.ParentId.Value);

    var totalCount = allMenus.Count();

    var items = allMenus
        .OrderBy(m => m.ParentId ?? int.MaxValue)
        .ThenBy(m => m.Sort)
        .Skip((request.PageIndex - 1) * request.PageSize)
        .Take(request.PageSize)
        .Select(m => new MenuFlatDto
        {
          Id = m.Id,
          Name = m.Name,
          Path = m.Path,
          Icon = m.Icon,
          ParentId = m.ParentId,
          Sort = m.Sort
        })
        .ToList();

    return ApiResult<PagedResult<MenuFlatDto>>.Success(new PagedResult<MenuFlatDto>
    {
      Items = items,
      TotalCount = totalCount,
      PageIndex = request.PageIndex,
      PageSize = request.PageSize
    });
  }
}